package com.kmzx.one.project.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import com.kmzx.one.common.exceptions.NoSuchObjectException;
import com.kmzx.one.common.exceptions.ParameterNullException;
import com.kmzx.one.common.utils.MD5Util;
import com.kmzx.one.common.utils.ServletUtils;
import com.kmzx.one.common.utils.StringUtils;
import com.kmzx.one.common.utils.UUIDGenerator;
import com.kmzx.one.project.config.data.QiNiuConfig;
import com.kmzx.one.project.config.data.WXDataConfig;
import com.kmzx.one.project.entity.AttributeValues;
import com.kmzx.one.project.entity.AttributeWithCategory;
import com.kmzx.one.project.entity.ProductAttribute;
import com.kmzx.one.project.entity.ProductAttributeValues;
import com.kmzx.one.project.entity.UserSharePics;
import com.kmzx.one.project.mapper.CustomerMapper;
import com.kmzx.one.project.mapper.ProductMapper;
import com.kmzx.one.project.mapper.SimpleMapper;
import com.kmzx.one.project.mapper.UserRankMapper;
import com.kmzx.one.project.others.common.FeeData;
import com.kmzx.one.project.others.common.IdAndKinds;
import com.kmzx.one.project.others.common.IdAndTitle;
import com.kmzx.one.project.others.common.Options;
import com.kmzx.one.project.others.common.ProdAndAttr;
import com.kmzx.one.project.others.dso.ProdCatePriceDso;
import com.kmzx.one.project.others.dso.ProdJoinAttributeCategory;
import com.kmzx.one.project.others.dso.ProdJoinAttributeWithCategory;
import com.kmzx.one.project.others.dso.ProdJoinDiscount;
import com.kmzx.one.project.others.dso.ProductExtraInfo;
import com.kmzx.one.project.others.dso.UserRankDso;
import com.kmzx.one.project.others.dto.*;
import com.kmzx.one.project.others.wxo.MySelfCodeUnLimit;
import com.kmzx.one.project.service.ProdService;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import weixin.popular.api.TokenAPI;
import weixin.popular.api.WxaAPI;
import weixin.popular.bean.token.Token;
import weixin.popular.bean.wxa.LineColor;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class ProdServiceImpl implements ProdService {


    protected final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private RedisTemplate<String, Object> objectRedisTemplate;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private SimpleMapper simpleMapper;

    @Autowired
    private CustomerMapper customerMapper;


    // 数据配置
    @Autowired
    private QiNiuConfig qiNiuConfig;

    @Autowired
    private WXDataConfig wxConfig;

    @Autowired
    private AtomicInteger atomicInteger;

    @Autowired
    UserRankMapper userRankMapper;

    public String getRankId(String userId) {
        List<UserRankDso> dsos = userRankMapper.selectAllRankTabs();
        String rankId = dsos.get(0).getRankId();
        if (userId != null && !userId.equals("")) {
            UserRankInfo info = userRankMapper.selectUserRankTabs(userId);
            String rankId1 = info.getRankId();
            rankId = rankId1;
        }

        return rankId;
    }

    // 查找所有的产品分类
    @Override
    public List<ProdCateOutInfo> findCateAll(String userId) {
        String rankId = getRankId(userId);
        List<ProdCateOutInfo> infos = productMapper.selectCateByRankId(rankId);
        return infos;
    }

    @Override
    public List<ProdOutInfo> findProdByCateIdPager() throws Exception {
        String cateId = ServletUtils.getParameter("cateId");
        String userId = ServletUtils.getParameter("userId");
        Integer pageNum = ServletUtils.getRequestPageNum();
        Integer pageSize = ServletUtils.getRequestPageSize();

        pageNum = pageNum == null ? 1 : pageNum;
        pageSize = pageSize == null ? 10 : pageSize;

        if (StringUtils.isEmpty(cateId)) {
            throw new ParameterNullException("cateId为空");
        }

        PageHelper.startPage(pageNum, pageSize, true);
        Page<ProdOutInfo> result = productMapper.selectProdByCateIdPager(cateId);
        List<ProdOutInfo> end = result.getResult();
        if (end == null) {
            return Collections.emptyList();
        } else {
            String rankId = getRankId(userId);
            List<ProdCateOutInfo> infos = productMapper.selectCateByRankId(rankId);
            if (infos != null && infos.size() > 0) {
                List<Integer> collect = infos.stream().map(lt -> lt.getCateId()).collect(Collectors.toList());
                if (!collect.contains(Integer.valueOf(cateId))) {
                    return Collections.emptyList();
                }
            }


            List<String> prodIds = end.stream().map(qq -> qq.getProdId()).collect(Collectors.toList());
            List<ProdCatePriceDso> priceDsos = productMapper.selectProdGroupPriceList(prodIds);


            // 所有的商品打折活动,包括所有的商品
            List<ProdJoinDiscount> discounts = productMapper.selectAllProductJoinDiscount();

            boolean specific = false;
            List<String> specUsers = customerMapper.findSpecificUser();
            if (!CollectionUtils.isEmpty(specUsers) && (userId != null && userId != "")) {
                if (specUsers.contains(userId)) {
                    specific = true;
                }
            }
            if (!CollectionUtils.isEmpty(priceDsos)) {
                Map<String, List<ProdCatePriceDso>> map = priceDsos.stream().collect(Collectors.groupingBy(ProdCatePriceDso::getProductId));


                if (specific) {
                    for (ProdOutInfo prod : end) {
                        List<ProdCatePriceDso> prodCatePriceDsos = map.get(prod.getProdId());
                        if (prodCatePriceDsos != null) {
                            BigDecimal miniCost = prodCatePriceDsos.get(0).getMiniCost();
                            prod.setProdPrice(miniCost);
                            prod.setCurrentPrice(miniCost);
                            prod.setBeauty(miniCost);
                            prod.setHas(prodCatePriceDsos.get(0).getNomNumbers() > 0);
                        } else {
                            prod.setProdPrice(BigDecimal.ONE);
                            prod.setCurrentPrice(BigDecimal.ONE);
                            prod.setBeauty(BigDecimal.ONE);
                        }
                    }
                } else {
                    for (ProdOutInfo prod : end) {
                        List<ProdCatePriceDso> prodCatePriceDsos = map.get(prod.getProdId());
                        if (prodCatePriceDsos != null) {
                            BigDecimal miniPrice = prodCatePriceDsos.get(0).getMiniPrice();
                            prod.setHas(prodCatePriceDsos.get(0).getNomNumbers() > 0);
                            prod.setProdPrice(miniPrice);
                            prod.setCurrentPrice(miniPrice);
                            prod.setBeauty(miniPrice);
                        } else {
                            BigDecimal price = productMapper.selectProdGroupPrice(prod.getProdId());
                            if (price != null) {
                                prod.setProdPrice(price);
                                prod.setCurrentPrice(price);
                                prod.setBeauty(price);
                            } else {
                                prod.setProdPrice(BigDecimal.ONE);
                                prod.setCurrentPrice(BigDecimal.ONE);
                                prod.setBeauty(BigDecimal.ONE);
                            }
                        }
                    }
                    switchToFastProd(end, userId, discounts);
                }
            }
            return end;
        }
    }


    public List<ProdOutInfo> switchToFastProd(List<ProdOutInfo> end, String userId, List<ProdJoinDiscount> discounts) {
        //
        List<StraightInfo> infoList = productMapper.selectAllStraightInfo();
        if (infoList == null) {
            if (!CollectionUtils.isEmpty(discounts)) {
                Map<String, List<ProdJoinDiscount>> listMap = discounts.stream().collect(Collectors.groupingBy(ProdJoinDiscount::getProductId));

                for (ProdOutInfo prod : end) {
                    String prodId = prod.getProdId();
                    List<ProdJoinDiscount> joinDiscounts = listMap.get(prodId);
                    if (joinDiscounts != null) {
                        Integer discountCate = joinDiscounts.get(0).getDiscountCate();
                        prod.setKinds(1);
                        // 0折扣  1 一口价
                        if (discountCate == 0) {
                            prod.setCurrentPrice(prod.getProdPrice().multiply(joinDiscounts.get(0).getDiscountNum()));
                        } else if (discountCate == 1) {
                            prod.setCurrentPrice(joinDiscounts.get(0).getDiscountNum());
                        }
                        prod.setBeauty(prod.getCurrentPrice());
                        prod.setDiscountImg(joinDiscounts.get(0).getDiscountImg());
                    }
                }
            }
            return end;
        }
        if (infoList != null && infoList.size() > 0) {
            UserRankInfo userRankInfo = userRankMapper.selectUserRankTabs(userId);
            boolean had = false;
            if (userRankInfo != null) {

                List<FastProdInfo> fastProdList = new ArrayList<>();
                for (StraightInfo info : infoList) {
                    had = true;
                    String id = info.getId();
                    Page<FastProdInfo> infos = productMapper.selectFastProdInfoPaged(id);
                    fastProdList.addAll(infos.getResult());
                }
                if (had) {
                    for (ProdOutInfo prodOutInfo : end) {
                        for (FastProdInfo fastProdInfo : fastProdList) {
                            if (prodOutInfo.getProdId().equals(fastProdInfo.getProdId())) {
                                prodOutInfo.setFastIcon(fastProdInfo.getFastIcon());
                                prodOutInfo.setCurrentPrice(fastProdInfo.getCurrentPrice());
                                prodOutInfo.setBeauty(fastProdInfo.getBeauty());
                                prodOutInfo.setKinds(2);
                            }
                        }
                    }
                }
            } else {
                had = true;
                List<FastProdInfo> fastProdList = new ArrayList<>();
                for (StraightInfo info : infoList) {
                    String id = info.getId();
                    Page<FastProdInfo> infos = productMapper.selectFastProdInfoPaged(id);
                    fastProdList.addAll(infos.getResult());
                }
                if (had) {
                    for (ProdOutInfo prodOutInfo : end) {
                        for (FastProdInfo fastProdInfo : fastProdList) {
                            if (prodOutInfo.getProdId().equals(fastProdInfo.getProdId())) {
                                prodOutInfo.setFastIcon(fastProdInfo.getFastIcon());
                                prodOutInfo.setCurrentPrice(fastProdInfo.getCurrentPrice());
                                prodOutInfo.setBeauty(fastProdInfo.getBeauty());
                                prodOutInfo.setKinds(2);
                            }
                        }
                    }
                }
            }
        }
        return end;
    }


    @Override
    public ProdMainInfo findProdMainInfo(String productId, String userId) throws Exception {

        List<String> specUsers = customerMapper.findSpecificUser();
        if (!CollectionUtils.isEmpty(specUsers) && (userId != null && userId != "")) {

            if (specUsers.contains(userId)) {
                // 有特权,有用户,也是
                ProdMainInfo prodMainInfo = findProdMainInfo(productId, userId, true);
                return prodMainInfo;
            } else { // 有特权,有用户,但不是
                ProdMainInfo prodMainInfo = findProdMainInfo(productId, userId, false);
                return prodMainInfo;
            }
        } else {
            // 没特权,没用户
            // 有特权,没用户
            ProdMainInfo prodMainInfo = findProdMainInfo(productId, userId, false);
            return prodMainInfo;
        }
    }

    @Override
    public ProdSpecsInfo findProdEntryInfo(String productId, String userId, String fastId, int outInner) throws Exception {

        List<ProdJoinAttributeCategory> joinAttributes = productMapper.selectProdEntryInfo(productId);
        List<ProdJoinDiscount> discounts = productMapper.selectProductJoinDiscount(productId);
        if (!CollectionUtils.isEmpty(joinAttributes)) {
            ProdJoinAttributeCategory joinAttributeCategory = joinAttributes.get(0);
            // 属性的Key
            String optionNameIds = joinAttributeCategory.getAllAttributeId();
            // 属性的Value
            String optionValueIds = joinAttributeCategory.getAllValuesId();
            String[] nameArray = optionNameIds.split(",");
            String[] idArray = optionValueIds.split(",");

            List<String> nameList = Arrays.asList(nameArray);
            List<String> idList = Arrays.asList(idArray);

            List<AttributeValues> attributeValuesList = productMapper.selectAttributeValuesByValueLists(nameList);

            List<ProductAttribute> productAttributeList = productMapper.selectProductAttributeLists(nameList);


            List<ProductAttributeValues> productAttributeValuesList = productMapper.selectProductAttributeValuesLists(idList);

            Map<String, List<AttributeValues>> nameIdListsMap = attributeValuesList.stream().collect(Collectors.groupingBy(AttributeValues::getNameId));
            HashMap<String, String> comName = new HashMap<>();
            ArrayList<ProdAndAttr> infos = new ArrayList<>();
            ArrayList<String> skuList = new ArrayList<>();
            // 直升商品
            UserRankInfo userRankInfo = userRankMapper.selectUserRankTabs(userId);
            if (userRankInfo != null) {
                int rankNum = userRankInfo.getRankNum();
                if (rankNum != 3) {
                    List<MemberActionInfo> actionInfos = productMapper.selectProductStraight();
                    if (!CollectionUtils.isEmpty(actionInfos)) {
                        List<Map<String, Object>> list = productMapper.selectProdFastKind(productId, rankNum);
                        if (list != null && list.size() > 0) {
                            for (Map<String, Object> objectMap : list) {
                                String skuId = (String) objectMap.get("skuId");
                                skuList.add(skuId);
                            }
                        }
                    }
                }
            }
            for (int i = 0; i < nameArray.length; i++) {

                List<AttributeValues> values = nameIdListsMap.get(nameArray[i]);
                ProdAndAttr attr = new ProdAndAttr();
                String nameId = values.get(0).getNameId();
                attr.setAttrId(nameId);

                for (ProductAttribute nameIdList : productAttributeList) {
                    if (nameId.equals(nameIdList.getId())) {
                        attr.setAttrName(nameIdList.getAttributeCategoryName());
                    }
                }
                ArrayList<IdAndTitle> idAndTitles = new ArrayList<>();
                for (ProductAttributeValues value : productAttributeValuesList) {
                    String valueId = value.getId();
                    String categoryValue = value.getCategoryValue();
                    String cateImg = value.getCateImg();
                    comName.put(valueId, categoryValue);
                    for (AttributeValues attributeValues : values) {
                        String valuesValueId = attributeValues.getValueId();
                        if (valueId.equals(valuesValueId)) {
                            IdAndTitle idAndTitle = new IdAndTitle();
                            idAndTitle.setId(valueId);
                            idAndTitle.setTitle(categoryValue);
                            idAndTitle.setIcons(cateImg);
                            if (!org.springframework.util.StringUtils.isEmpty(cateImg)) {
                                idAndTitle.setHad(1);
                            }
                            idAndTitles.add(idAndTitle);
                        }

                    }
                }
                attr.setChilds(idAndTitles);
                attr.setChildren(idAndTitles);
                infos.add(attr);
            }
            List<AttributeWithCategory> attributeWithCategories = productMapper.selectOptionIdAndValueKeys(joinAttributeCategory.getKinds());

            HashMap<String, Integer> hashMap = new HashMap<>();

            List<WareHouseInfo> houseInfos = productMapper.selectProdStore(productId);

            if (!CollectionUtils.isEmpty(houseInfos)) {

                for (WareHouseInfo info : houseInfos) {
                    String id = info.getAttributeWithCategoryId();
                    Integer infoNum = hashMap.get(id);
                    if (infoNum != null) {
                        hashMap.put(id, infoNum + info.getNowNumber());
                    } else {
                        hashMap.put(id, info.getNowNumber());
                    }
                }

            }
            boolean has = false;
            if (!CollectionUtils.isEmpty(discounts)) {
                has = true;
            }
            ArrayList<Options> dtos = new ArrayList<>();
            List<FastProdInfo> result = productMapper.selectFastProdInfoPagedList2();
            boolean flag = false;
            if (result != null && result.size() > 0) {
                flag = true;
            }
            for (AttributeWithCategory key : attributeWithCategories) {
                String valuesId = key.getAllAttributeValuesId();
                String awcId = key.getId();
                Options dto = new Options();
                dto.setCombineId(valuesId);
                dto.setProdPrice(key.getPrice());
                dto.setCurrentPrice(key.getPrice());
                dto.setKinds(0);


//                dto.setPrice(key.getPrice());
//                dto.setOldPrice(key.getPrice());

//                dto.setDiscountCate(0);
//                dto.setDiscountNum(BigDecimal.ONE);
                if (has) {
                    BigDecimal prodPrice = dto.getProdPrice();
                    List<ProdJoinDiscount> joinDiscounts = discounts.stream().filter(ll -> ll.getSkuId().equals(awcId)).collect(Collectors.toList());
                    if (joinDiscounts != null && joinDiscounts.size() > 0) {
                        ProdJoinDiscount pjd = joinDiscounts.get(0);
                        if (pjd != null) {
                            Integer cate = joinDiscounts.get(0).getDiscountCate();
                            BigDecimal discountNum = joinDiscounts.get(0).getDiscountNum();
//                            dto.setDiscountCate(cate);
//                            dto.setDiscountNum(discountNum);
                            if (cate == 1) {
                                dto.setKinds(1);
                                dto.setCurrentPrice(discountNum);
                            } else {
                                if(discountNum.compareTo(BigDecimal.ONE)!=0){
                                    dto.setCurrentPrice(prodPrice.multiply(discountNum));
                                    dto.setKinds(1);
                                }
                            }
                        }
                    }
                }
                dto.setBeauty(dto.getCurrentPrice());
                String[] ls = valuesId.split(",");
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < ls.length; i++) {
                    builder.append(comName.get(ls[i]) + ",");
                }
                dto.setCombineName(builder.substring(0, builder.length() - 1));
                List<String> op = Arrays.asList(ls);
                dto.setIdArray(op);
                dto.setId(awcId);
                Integer infoNum = hashMap.get(awcId);
                if (infoNum != null) {
                    dto.setHas(true);
                    dto.setNumber(infoNum);
                } else {
                    dto.setHas(false);
                }
//                hashMap.put(key.getId(), dto);
                if (skuList != null && skuList.size() > 0) {
                    boolean contains = skuList.contains(awcId);
                    dto.setCar(!contains);
                    dto.setFast(contains);
                    if (contains) {
//                        dto.setDiscountCate(1);
                        BigDecimal upPrice = productMapper.selectFastProdBySku(awcId);
                        dto.setCurrentPrice(upPrice);
                        dto.setKinds(2);
                        dto.setBeauty(upPrice);
//                        dto.setDiscountNum(upPrice);
                    }
                } else {
                    dto.setCar(true);
                }
                dtos.add(dto);
            }
            ProdSpecsInfo details = new ProdSpecsInfo();
            details.setProductName(joinAttributes.get(0).getProductName());
            details.setProdName(joinAttributes.get(0).getProductName());
            details.setProdId(productId);
            details.setOptionsCount(nameArray.length);
            details.setInfos(infos);
//          details.setKvs(hashMap);
            details.setKvMoney(dtos);
            List<String> specUsers = customerMapper.findSpecificUser();

            if (!CollectionUtils.isEmpty(specUsers) && (userId != null && userId != "") && (specUsers.contains(userId) && !CollectionUtils.isEmpty(houseInfos))) {
                for (Options dto : dtos) {
                    String id = dto.getId();
                    List<WareHouseInfo> in = houseInfos.stream().filter(lg -> lg.getAttributeWithCategoryId().equals(id)).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(in)) {
                        dto.setCurrentPrice(in.get(0).getEnterCost());
//                        dto.setOldPrice(in.get(0).getEnterCost());

                        dto.setProdPrice(in.get(0).getEnterCost());
//                        dto.setCurrentPrice(in.get(0).getEnterCost());
                    }
                }
            }
            return details;
        }
        return null;
    }

    @Override
    public String doShareGoods(String userId, String productId, String fast) throws Exception {

        if (userId == null || (userId != null && userId == "")) {
            throw new NoSuchObjectException("该用户信息不存在");
        }
        if (fast == null || "".equals(fast)) {
            fast = "false";
        }
        List<UserSharePics> userSharePics = simpleMapper.selectUserSharePics(userId, productId, fast);

        if (!CollectionUtils.isEmpty(userSharePics)) {
            UserSharePics pics = userSharePics.get(0);
            return pics.getShareImg();
        }


        String scene = MD5Util.MD5Encode(productId + "/" + userId + "/" + fast, null);
        MySelfCodeUnLimit getwxacodeunlimit = new MySelfCodeUnLimit();

        getwxacodeunlimit.setAuto_color(true);
        getwxacodeunlimit.setScene(scene);
        getwxacodeunlimit.setWidth(430);
        getwxacodeunlimit.setPage("pages/gift_details/gift_details");
        LineColor lineColor = new LineColor();
        lineColor.setR("");
        lineColor.setG("");
        lineColor.setB("");
        getwxacodeunlimit.setIs_hyaline(true);
        getwxacodeunlimit.setLine_color(lineColor);

        BufferedImage bufferedImage = WxaAPI.getwxacodeunlimit(getRightAccessToken(), getwxacodeunlimit);

        String sendImg = "";

        logger.info("bufferedImage.toString() = " + bufferedImage.toString());


        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageOutputStream imageOutput = ImageIO.createImageOutputStream(byteArrayOutputStream);
        ImageIO.write(bufferedImage, "png", imageOutput);
        InputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        String png = generateFileName("png");
        String fullPath = "kmzx/share/" + png;
        asyncUpload(fullPath, byteArrayInputStream);
        String sendPath = qiNiuConfig.getDomainHost() + fullPath;


        sendImg = sendPath;
        UserSharePics qrCode = new UserSharePics();
        qrCode.setId(UUIDGenerator.generate())
                .setUserId(userId)
                .setProductId(productId)
                .setCreateTime(new Date())
                .setShareImg(sendImg)
                .setRemarks(fast)
                .setOptions(getwxacodeunlimit.getScene())
                .setStates(0);
        simpleMapper.insertUserSharePics(qrCode);
        return sendImg;
    }

    @Override
    public Map<String, String> doSceneToProduct(String scene) throws Exception {

        Map<String, String> product = simpleMapper.selectSceneByProdId(scene);
        if (!CollectionUtils.isEmpty(product)) {
            return product;
        }
        return null;
    }




    public String generateFileName(String fileType) {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        StringBuilder sb = new StringBuilder();
        sb.append(year);
        sb.append("/");
        sb.append(calendar.get(Calendar.MONTH) + 1);
        sb.append("/");
        sb.append(calendar.get(Calendar.DAY_OF_MONTH));
        sb.append("-");
        sb.append(calendar.get(Calendar.HOUR_OF_DAY));// 1位
        sb.append(calendar.get(Calendar.MINUTE));// 1位
        sb.append(calendar.get(Calendar.SECOND));// 1位
        sb.append("-");
        sb.append(atomicInteger.getAndIncrement());
        sb.append(RandomStringUtils.randomAlphanumeric(6));
        sb.append(".");
        sb.append(fileType);
        return sb.toString();
    }


    /**
     * 异步上传数据
     *
     * @param fileName
     * @param input
     */
    public void asyncUpload(String fileName, InputStream input) {
        Configuration cfg = new Configuration(Zone.huanan());
        UploadManager uploadManager = new UploadManager(cfg);
        String accessKey = qiNiuConfig.getAppKey();
        String secretKey = qiNiuConfig.getAppSecret();
        String bucket = qiNiuConfig.getBucketName1();
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(input, fileName, upToken, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            logger.info("请求返回的数据key:{}", putRet.key);
            logger.info("请求返回的数据Hash:{}", putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
            }
        }
    }

    public String getRightAccessToken() {
        Object obj = objectRedisTemplate.opsForValue().get("messageToken");
        String wxTokens = null;
        if (obj != null) {
            String mt = (String) obj;
            wxTokens = mt;
        } else {
            Token token = TokenAPI.token(wxConfig.getAppId(), wxConfig.getAppSecret());
            String access_token = token.getAccess_token();
            int secend = token.getExpires_in();
            wxTokens = access_token;
            objectRedisTemplate.opsForValue().set("messageToken", access_token, 7000, TimeUnit.SECONDS);
        }
        return wxTokens;
    }

    // 3.1 查看商品的主要信息
    public ProdMainInfo findProdMainInfo(String productId, String userId, boolean has) throws Exception {
        List<ProdJoinAttributeWithCategory> joinAttributes = productMapper.selectProdEntryInfo2(productId);
        BigDecimal minPrice = productMapper.findProductSpecificMinPrice(productId);
        // 所有的商品打折活动,包括所有的商品
        List<ProdJoinDiscount> discounts = productMapper.selectAllProductJoinDiscount();
        if (!CollectionUtils.isEmpty(joinAttributes)) {

            ProdJoinAttributeWithCategory joinAttribute = joinAttributes.get(0);
            ProdMainInfo result = new ProdMainInfo();
            result.setEnabled(joinAttribute.getStates());
            Integer inOrOut = joinAttribute.getInOrOut();
            result.setInOrOut(inOrOut);
            result.setCurrentPrice(joinAttributes.stream().sorted(Comparator.comparing(ProdJoinAttributeWithCategory::getPrice)).findFirst().get().getPrice());
            result.setProdPrice(result.getCurrentPrice());
            if (discounts != null && discounts.size() > 0) {
                Map<String, List<ProdJoinDiscount>> listMap = discounts.stream().collect(Collectors.groupingBy(ProdJoinDiscount::getProductId));
                List<ProdJoinDiscount> discountList = listMap.get(productId);
                if (discountList != null && discountList.size() > 0) {
                    ProdJoinDiscount discount = discountList.get(0);

                    // 固定折扣
                    result.setDiscountCate(discount.getDiscountCate());
                    BigDecimal currentPrice = result.getCurrentPrice();
                    if (discount.getDiscountCate() == 0) {
                        result.setDiscountNum(discount.getDiscountNum().doubleValue());
                        result.setCurrentPrice(currentPrice.multiply(discount.getDiscountNum()));
                    } else {
                        result.setCurrentPrice(discount.getDiscountNum());
                        result.setDiscountNum(1.0);
                    }
                } else {
                    result.setDiscountNum(1.0);
                }
            }


            if (has && minPrice != null) {
                // 特权的最小价格
                result.setCurrentPrice(minPrice);
                result.setProdPrice(minPrice);
            } else {
                // 直升商品
//                UserRankInfo userRankInfo = userRankMapper.selectUserRankTabs(userId);


                List<MemberActionInfo> actionInfos = productMapper.selectProductStraight();
                if (!CollectionUtils.isEmpty(actionInfos)) {
                    List<Map<String, Object>> list = productMapper.selectProdFastKind(productId, 0);

                    if (!CollectionUtils.isEmpty(list)) {
                        for (Map<String, Object> objectMap : list) {
                            Double growthValue = (Double) objectMap.get("growthValue");
                            result.setBeauty(BigDecimal.valueOf(growthValue));
                            BigDecimal upMoney = (BigDecimal) objectMap.get("upMoney");
                            result.setCurrentPrice(upMoney);
                            result.setDiscountCate(1);
                            result.setDiscountNum(upMoney.doubleValue());
                        }
                    }
                }


            }

            BigDecimal productFreight = joinAttribute.getProductFreight();
            if (productFreight == null) {
                productFreight = BigDecimal.ZERO;
            }
            BigDecimal tariffFree = joinAttribute.getTariffFree();
            if (tariffFree == null) {
                tariffFree = BigDecimal.ZERO;
            }
            result.setProdId(productId).setProdName(joinAttribute.getProductName()).setExpressFee(productFreight).setTariffFee(tariffFree);

            List<IdAndKinds> pics = productMapper.selectProdPicsByProdId(productId);

            if (!CollectionUtils.isEmpty(pics)) {
                result.setCarouselsImg(pics.stream().filter(a -> a.getKinds() == 1).map(b -> b.getId()).collect(Collectors.toList()));
                result.setDetailImg(pics.stream().filter(a -> a.getKinds() == 2).map(b -> b.getId()).collect(Collectors.toList()));
            }

            Map<String, BigDecimal> freeFee = productMapper.selectProductFreeFee();
            Integer po = productMapper.selectProdAttributeStoreId3(productId);
            if (po != null && po != 0) {
                result.setHas(true);
            }


            int isFast = productMapper.checkProdIsFast(productId);
            if (isFast > 0) {
                result.setFast(true);
            }
            result.setFullMoney(freeFee.get("fullMoney"));
            result.setPayMoney(freeFee.get("payMoney"));

            result.setExtraRate(BigDecimal.ZERO);
            result.setExtraMoney(BigDecimal.ZERO);
            if (inOrOut == 1) {
                List<ProductExtraInfo> extraInfos = productMapper.selectProdExtraInfo("");
                if (!CollectionUtils.isEmpty(extraInfos)) {
                    ProductExtraInfo extraInfo = extraInfos.get(0);
                    result.setExtraRate(BigDecimal.valueOf(extraInfo.getChargesNumber()));
                    result.setExtraMoney(extraInfo.getChargesPrice());
                }
            }
            return result;
        }
        return null;
    }

    @Override
    public FastZoneInfo findStraightListProduct(String fastId, String userId, Integer pageNum, Integer pageSize) {
        if (userId == null || userId == "") {
            StraightInfo fastInfo = productMapper.selectStraightInfoById(fastId);
            if (fastInfo == null) {
                throw new ParameterNullException("直升物品暂无!");
            }
            FastZoneInfo zoneInfo = new FastZoneInfo();
            zoneInfo.setFastId(fastId).setRankId("").setRankNum(0);
            zoneInfo.setHeaderImg(fastInfo.getStraightImg4());


            PageHelper.startPage(pageNum, pageSize, true);
            Page<FastProdInfo> paged = productMapper.selectFastProdInfoPaged(fastId);
            List<FastProdInfo> result = paged.getResult();
            if (result != null && result.size() > 0) {
                List<String> prodIds = result.stream().map(qq -> qq.getProdId()).collect(Collectors.toList());
                List<ProdCatePriceDso> priceDsos = productMapper.selectProdGroupPriceList(prodIds);
                if (!CollectionUtils.isEmpty(priceDsos)) {
                    Map<String, List<ProdCatePriceDso>> map = priceDsos.stream().collect(Collectors.groupingBy(ProdCatePriceDso::getProductId));
                    for (FastProdInfo prodInfo : result) {
                        List<ProdCatePriceDso> prodCatePriceDsos = map.get(prodInfo.getProdId());
                        prodInfo.setKinds(2);
                        prodInfo.setHas(prodCatePriceDsos.get(0).getNomNumbers() > 0);
                    }
                }
            }
            zoneInfo.setChildren(result);
            return zoneInfo;
        } else {
            if (checkSuper(userId)) {
                return null;
            }
            UserRankInfo userRankInfo = userRankMapper.selectUserRankTabs(userId);
            int rankNum = userRankInfo.getRankNo();
            StraightInfo fastInfo = productMapper.selectStraightInfoById(fastId);
            if (fastInfo == null) {
                throw new ParameterNullException("直升物品暂无!");
            }

            FastZoneInfo zoneInfo = new FastZoneInfo();
            zoneInfo.setFastId(fastId).setRankId(userRankInfo.getRankId()).setRankNum(rankNum);
            zoneInfo.setHeaderImg(fastInfo.getStraightImg4());


            PageHelper.startPage(pageNum, pageSize, true);
            Page<FastProdInfo> paged = productMapper.selectFastProdInfoPaged(fastId);
            List<FastProdInfo> result = paged.getResult();
            if (result != null && result.size() > 0) {
                List<String> prodIds = result.stream().map(qq -> qq.getProdId()).collect(Collectors.toList());
                List<ProdCatePriceDso> priceDsos = productMapper.selectProdGroupPriceList(prodIds);
                if (!CollectionUtils.isEmpty(priceDsos)) {
                    Map<String, List<ProdCatePriceDso>> map = priceDsos.stream().collect(Collectors.groupingBy(ProdCatePriceDso::getProductId));
                    for (FastProdInfo prodInfo : result) {
                        prodInfo.setKinds(2);
                        List<ProdCatePriceDso> prodCatePriceDsos = map.get(prodInfo.getProdId());
                        if(prodCatePriceDsos!=null && prodCatePriceDsos.size()>0){
                            prodInfo.setHas(prodCatePriceDsos.get(0).getNomNumbers() > 0);
                        }else {
                            prodInfo.setHas(false);
                        }
                    }
                }
            }
            zoneInfo.setChildren(result);
            return zoneInfo;
        }
    }

    @Override
    public FastProdMainInfo selectFastProdMainInfo(String prodId, String skuId, String userId) {
        if (checkSuper(userId)) {
            return null;
        }
        List<ProdJoinAttributeWithCategory> joinAttributes = productMapper.selectProdEntryInfo2(prodId);
        if (!CollectionUtils.isEmpty(joinAttributes)) {
            ProdJoinAttributeWithCategory joinAttribute = joinAttributes.get(0);
            FastProdMainInfo result = new FastProdMainInfo();
            result.setEnabled(joinAttribute.getStates());
            Integer inOrOut = joinAttribute.getInOrOut();
            result.setInOrOut(inOrOut);
            result.setKinds(2);
            result.setProdPrice(joinAttribute.getPrice());
            result.setCurrentPrice(result.getProdPrice());

            BigDecimal productFreight = joinAttribute.getProductFreight();
            if (productFreight == null) {
                productFreight = BigDecimal.ZERO;
            }
            BigDecimal tariffFree = joinAttribute.getTariffFree();
            if (tariffFree == null) {
                tariffFree = BigDecimal.ZERO;
            }
            result.setProdId(prodId).setProdName(joinAttribute.getProductName()).setExpressFee(productFreight).setTariffFee(tariffFree);

            List<IdAndKinds> pics = productMapper.selectProdPicsByProdId(prodId);

            if (!CollectionUtils.isEmpty(pics)) {
                result.setCarouselsImg(pics.stream().filter(a -> a.getKinds() == 1).map(b -> b.getId()).collect(Collectors.toList()));
                result.setDetailImg(pics.stream().filter(a -> a.getKinds() == 2).map(b -> b.getId()).collect(Collectors.toList()));
            }

            Map<String, BigDecimal> freeFee = productMapper.selectProductFreeFee();
            Integer po = productMapper.selectProdAttributeStoreId3(prodId);
            if (po != null && po != 0) {
                result.setHas(true);
            }
            result.setFullMoney(freeFee.get("fullMoney"));
            result.setPayMoney(freeFee.get("payMoney"));


            result.setExGateFullMoney(freeFee.get("fullMoney"));
            result.setExGateAppendMoney(freeFee.get("payMoney"));

//            result.setExtraRate(BigDecimal.ZERO);
//            result.setExtraMoney(BigDecimal.ZERO);
            if (inOrOut == 1) {
                List<ProductExtraInfo> extraInfos = productMapper.selectProdExtraInfo("");
                if (!CollectionUtils.isEmpty(extraInfos)) {
                    ProductExtraInfo extraInfo = extraInfos.get(0);
//                    result.setExtraRate(BigDecimal.valueOf(extraInfo.getChargesNumber()));
//                    result.setExtraMoney(extraInfo.getChargesPrice());
                    int toUse = extraInfo.getToUse();
                    int toUse2 = extraInfo.getToUse2();
                    if(toUse==1){
                        result.setExFee(extraInfo.getChargesPrice());
                    }
                    if (toUse2==1) {
                        result.setGateFeeRate(BigDecimal.valueOf(extraInfo.getChargesNumber()));
                    }
                }
            }
            return result;
        }
        return null;
    }


    //  // 精选品牌

    @Override
    public FastZoneOutInfo findFastZone(String userId) {
        FastZoneOutInfo outInfo = new FastZoneOutInfo();
        outInfo.setUserId(userId).setFlag(0).setRankNum(0);
        List<MemberActionInfo> actionInfos = productMapper.selectProductStraight();
        if (userId == null || userId == "") {
            if (actionInfos != null && actionInfos.size() > 0) {
                outInfo.setFlag(1);
                outInfo.setVipImg(actionInfos.get(0).getPicOne());
                outInfo.setVipUrl(actionInfos.get(0).getFastId());
                if (actionInfos.size() == 2) {
                    outInfo.setSvipImg(actionInfos.get(1).getPicOne());
                    outInfo.setSvipUrl(actionInfos.get(1).getFastId());
                    outInfo.setFlag(3);
                }
            }
            return outInfo;
        } else {
            UserRankInfo userRankInfo = userRankMapper.selectUserRankTabs(userId);
            if (userRankInfo == null) {
                if (actionInfos != null && actionInfos.size() > 0) {
                    outInfo.setFlag(1);
                    outInfo.setRankNum(0);
                    outInfo.setVipImg(actionInfos.get(0).getPicOne());
                    outInfo.setVipUrl(actionInfos.get(0).getFastId());
                    if (actionInfos.size() == 2) {
                        outInfo.setSvipImg(actionInfos.get(1).getPicOne());
                        outInfo.setSvipUrl(actionInfos.get(1).getFastId());
                        outInfo.setFlag(3);
                    }
                }
                return outInfo;
            } else {
                int rankNum = userRankInfo.getRankNo();
                outInfo.setRankNum(rankNum);
                if (actionInfos.size() == 1) {
                    outInfo.setFlag(1);
                    outInfo.setVipImg(actionInfos.get(0).getPicOne());
                    outInfo.setVipUrl(actionInfos.get(0).getFastId());
                } else if (actionInfos.size() == 2) {
                    outInfo.setFlag(1);
                    outInfo.setVipImg(actionInfos.get(0).getPicOne());
                    outInfo.setVipUrl(actionInfos.get(0).getFastId());
                    outInfo.setSvipImg(actionInfos.get(1).getPicOne());
                    outInfo.setSvipUrl(actionInfos.get(1).getFastId());
                    outInfo.setFlag(3);
                }
            }
        }
        return outInfo;
    }

    public boolean checkSuper(String userId) {
        List<String> specUsers = customerMapper.findSpecificUser();
        if (!CollectionUtils.isEmpty(specUsers) && (userId != null && userId != "")) {
            if (specUsers.contains(userId)) {
                return true;
            }
        }
        return false;
    }
}
